﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Shared;
using System.ServiceModel;
using RastinArgham.Robots.Registration.RobotWCF;

namespace RastinArgham.Robots.Registration
{
    public partial class Browser : Form
    {

        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        public Register data { get; set; }
        public int interval { get; set; }
        public string url { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string special_username { get; set; }
        public string special_password { get; set; }

        public Browser()
        {
            timer.Enabled = false;
            timer.Tick += new EventHandler(timer_Tick);

            InitializeComponent();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();

            PrintHeader();

            try
            {
                switch (data.State)
                {
                    case RegisterState.Started:
                        Starting();
                        break;
                    case RegisterState.Login:
                        Login();
                        break;
                    case RegisterState.Search:
                        Search();
                        break;
                    case RegisterState.CheckSearchResult:
                        CheckSearchResult();
                        break;
                    case RegisterState.FillData_RequestType:
                        FillData_RequestType();
                        break;
                    case RegisterState.FillData_Personal:
                        FillData_Personal();
                        break;
                    case RegisterState.FillData_Personal_Speed:
                        FillData_Personal_Speed();
                        break;
                    case RegisterState.FillData_Company:
                        FillData_Company();
                        break;
                    case RegisterState.FillData_Address:
                        FillData_Address();
                        break;
                    case RegisterState.FillData_Address_City:
                        FillData_Address_City();
                        break;
                    case RegisterState.FillData_Install:
                        FillData_Install();
                        break;
                    case RegisterState.FillData_Install_City:
                        FillData_Install_City();
                        break;
                    case RegisterState.FillData_Service:
                        FillData_Service();
                        break;
                    case RegisterState.FillData_Service_Duration:
                        FillData_Service_Duration();
                        break;
                    case RegisterState.Submit:
                        Submit();
                        break;
                    case RegisterState.Success:
                        Success();
                        break;
                    default:
                        break;
                }

                PrintHeader();

                timer.Start();
            }
            catch (RobotException x)
            {
                timer.Stop();
                Log(x.Message);
                CRMRobotWCFClient wcfClient = new CRMRobotWCFClient();
                wcfClient.ContactRegistrationReport(data.OrderId, data.Identity, false, x.Message);
                Application.Exit();
            }
            catch (Exception ex)
            {
                timer.Stop();
                Log(ex.Message);
                String ErrorMessage = ex.ToString();

                try
                {
                    HtmlDocument doc = webBrowser.Document;
                    HtmlElement messageSearch = doc.GetElementById("ctl00_ContentPlaceHolder1_messageLbSearch");
                    if (messageSearch != null)
                        ErrorMessage = messageSearch.InnerText;
                    else if (doc.GetElementById("ctl00_ContentPlaceHolder1_MessageLbl") != null)
                        ErrorMessage = doc.GetElementById("ctl00_ContentPlaceHolder1_MessageLbl").InnerText;
                }
                catch
                {
                }

                CRMRobotWCFClient wcfClient = new CRMRobotWCFClient();
                wcfClient.ContactRegistrationReport(data.OrderId, data.Identity, false, ErrorMessage);
                Application.Exit();
            }
        }

        private void CheckSearchResult()
        {
            HtmlDocument doc = webBrowser.Document;
            HtmlElement message = doc.GetElementById("ctl00_ContentPlaceHolder1_messageLbSearch");

            if (message == null)
                data.State = RegisterState.FillData_RequestType;
            else
                throw new RobotException(message.InnerText);
        }

        private void Success()
        {
            HtmlDocument doc = webBrowser.Document;
            HtmlElement message = doc.GetElementById("ctl00_ContentPlaceHolder1_MessageLbl");
            if (!message.InnerText.Contains("ثبت اطلاعات با موفقيت انجام شد"))
                throw new Exception("Invalid Data!");

            Log("Success");

            CRMRobotWCFClient wcfClient = new CRMRobotWCFClient();
            wcfClient.ContactRegistrationReport(data.OrderId, data.Identity, true, null);

            Application.Exit();
        }

        private void Submit()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement submitBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$Registerbtn");
            //HtmlElement submitBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$btnCheckPrint");

            submitBtn.InvokeMember("click");

            data.State = RegisterState.Success;
        }

        private void FillData_Service_Duration()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement serviceduration = doc.GetElementById("ctl00$ContentPlaceHolder1$ServicesDurationDdl2");

            foreach (HtmlElement item in serviceduration.Children)
            {
                if (item.GetAttribute("value") == data.ServiceDuration.ToString())
                {
                    item.SetAttribute("selected", "selected");
                    break;
                }
            }

            data.State = RegisterState.Submit;
        }

        private void FillData_Service()
        {
            HtmlDocument doc = webBrowser.Document;

            //service
            HtmlElement producttitle = doc.GetElementById("ctl00$ContentPlaceHolder1$ProductsTitleDdl");
            if (producttitle == null)
            {
                data.State = RegisterState.FillData_Service_Duration;
                return;
            }

            foreach (HtmlElement item in producttitle.Children)
            {
                if (item.InnerText == data.ProductTitle)
                {
                    item.SetAttribute("selected", "selected");
                    break;
                }
            }

            producttitle.RaiseEvent("onchange");

            data.State = RegisterState.FillData_Service_Duration;
        }

        private void FillData_Install_City()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement placecity = doc.GetElementById("ctl00$ContentPlaceHolder1$INSTALL_PLACE_FK_CITY_ddl");

            foreach (HtmlElement item in placecity.Children)
            {
                if (item.GetAttribute("value") == data.PlaceCity.ToString())
                {
                    item.SetAttribute("selected", "selected");
                    break;
                }
            }

            data.State = RegisterState.FillData_Service;
        }

        private void FillData_Install()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement addressmodem = doc.GetElementById("ctl00$ContentPlaceHolder1$address_modem_txt");
            HtmlElement plaque = doc.GetElementById("ctl00$ContentPlaceHolder1$install_place_plaque_txt");
            HtmlElement buildingname = doc.GetElementById("ctl00$ContentPlaceHolder1$install_place_building_name_txt");
            HtmlElement placefloor = doc.GetElementById("ctl00$ContentPlaceHolder1$install_place_floor_txt");
            HtmlElement placevahednum = doc.GetElementById("ctl00$ContentPlaceHolder1$install_place_vahed_number_txt");
            HtmlElement placetelnum = doc.GetElementById("ctl00$ContentPlaceHolder1$install_place_tel_num_txt");


            addressmodem.InnerText = data.AddressModem;
            plaque.InnerText = data.Plaque;
            buildingname.InnerText = data.BuilidingName;
            placefloor.InnerText = data.PlaceFloor;
            placevahednum.InnerText = data.PlaceVahedNum;
            placetelnum.InnerText = data.PlaceTelNum;

            HtmlElement placeostan = doc.GetElementById("ctl00$ContentPlaceHolder1$install_place_ostan_ddl");

            foreach (HtmlElement item in placeostan.Children)
            {
                if (item.GetAttribute("value") == data.PlaceOstan.ToString())
                {
                    item.SetAttribute("selected", "selected");
                    break;
                }
            }

            placeostan.RaiseEvent("onchange");

            data.State = RegisterState.FillData_Install_City;
        }

        private void FillData_Address_City()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement city = doc.GetElementById("ctl00$ContentPlaceHolder1$cityDDL");

            foreach (HtmlElement item in city.Children)
            {
                if (item.GetAttribute("value") == data.City.ToString())
                {
                    item.SetAttribute("selected", "selected");
                    break;
                }
            }

            data.State = RegisterState.FillData_Install;

        }

        private void FillData_Address()
        {
            HtmlDocument doc = webBrowser.Document;

            //adress
            HtmlElement address = doc.GetElementById("ctl00$ContentPlaceHolder1$AddressIDTxt");
            HtmlElement postalcode = doc.GetElementById("ctl00$ContentPlaceHolder1$PostCodetxt");
            HtmlElement tel = doc.GetElementById("ctl00$ContentPlaceHolder1$Teltxt");
            HtmlElement mobile = doc.GetElementById("ctl00$ContentPlaceHolder1$Mobiletxt");
            HtmlElement fax = doc.GetElementById("ctl00$ContentPlaceHolder1$Faxtxt");
            HtmlElement email = doc.GetElementById("ctl00$ContentPlaceHolder1$email_txt");
            HtmlElement website = doc.GetElementById("ctl00$ContentPlaceHolder1$web_site_txt");

            address.InnerText = data.Address;
            postalcode.InnerText = data.PostalCode;
            tel.InnerText = data.Tel;
            mobile.InnerText = data.Mobile;
            fax.InnerText = data.Fax;
            email.InnerText = data.Email;
            website.InnerText = data.Webiste;

            HtmlElement region = doc.GetElementById("ctl00$ContentPlaceHolder1$regionDDL");

            foreach (HtmlElement item in region.Children)
            {
                if (item.GetAttribute("value") == data.PlaceOstan.ToString())
                {
                    item.SetAttribute("selected", "selected");
                    break;
                }
            }

            region.RaiseEvent("onchange");

            data.State = RegisterState.FillData_Address_City;
        }

        private void FillData_Company()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement companyname = doc.GetElementById("ctl00$ContentPlaceHolder1$CoNametxt");
            HtmlElement companyfullname = doc.GetElementById("ctl00$ContentPlaceHolder1$corp_full_name_txt");
            HtmlElement regno = doc.GetElementById("ctl00$ContentPlaceHolder1$RegNotxt");
            HtmlElement econimics = doc.GetElementById("ctl00$ContentPlaceHolder1$EconomicIDTxt");
            HtmlElement companymanagername = doc.GetElementById("ctl00$ContentPlaceHolder1$corp_manager_Name_txt");
            HtmlElement companymanagerlastname = doc.GetElementById("ctl00$ContentPlaceHolder1$corpManagerLastNameTxt");
            HtmlElement companymanagerfullname = doc.GetElementById("ctl00$ContentPlaceHolder1$corp_manager_full_name_en_txt");
            HtmlElement companymangermelicode = doc.GetElementById("ctl00$ContentPlaceHolder1$corp_manager_meli_code_txt");
            HtmlElement companymanagerbirthdate = doc.GetElementById("ctl00$ContentPlaceHolder1$corpManagerBirthDate$Txt_Dt");
            HtmlElement companymanagergrade = doc.GetElementById("ctl00$ContentPlaceHolder1$corp_manager_fk_ed_grade_ddl");
            HtmlElement companymanagermajor = doc.GetElementById("ctl00$ContentPlaceHolder1$corp_manager_major_txt");
            HtmlElement companybaseactivity = doc.GetElementById("ctl00$ContentPlaceHolder1$corp_base_activity_txt");

            companyname.InnerText = data.CompanyName;
            companyfullname.InnerText = data.CompanyFullName;
            regno.InnerText = data.RegNo;
            econimics.InnerText = data.Economics;
            companymanagername.InnerText = data.ManagerName;
            companymangermelicode.InnerText = data.ManagerMelliCode;
            companymanagerlastname.InnerText = data.ManagerLastName;
            companymanagerfullname.InnerText = data.ManagerFullname;
            companymanagerbirthdate.InnerText = data.ManagerBirthDate;
            companymanagermajor.InnerText = data.ManagerMajor;
            companybaseactivity.InnerText = data.CompanyBaseActivity;

            companymanagergrade.Children[data.CompanyManagerGrade].SetAttribute("selected", "selected");

            data.State = RegisterState.FillData_Address;
        }

        private void FillData_Personal_Speed()
        {
            HtmlDocument doc = webBrowser.Document;
            HtmlElement actualmadarek = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_madarek_DDL");

            foreach (HtmlElement item in actualmadarek.Children)
            {
                if (item.GetAttribute("value") == data.ActualMadarek.ToString())
                {
                    item.SetAttribute("selected", "selected");
                    break;
                }
            }

            data.State = RegisterState.FillData_Address;
        }

        private void FillData_Personal()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement name = doc.GetElementById("ctl00$ContentPlaceHolder1$Nametxt");
            HtmlElement lastname = doc.GetElementById("ctl00$ContentPlaceHolder1$customerNameLastTxt");
            HtmlElement fullname = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_full_name_txt");
            HtmlElement actualid = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_id_num_txt");
            HtmlElement mellicode = doc.GetElementById("ctl00$ContentPlaceHolder1$meli_code_txt");
            HtmlElement birthdate = doc.GetElementById("ctl00$ContentPlaceHolder1$ActualBirthDate$Txt_Dt");
            HtmlElement actualissue = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_issue_place_txt");
            HtmlElement fathername = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_father_name_txt");
            HtmlElement actualemploy = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_employ_txt");
            HtmlElement managergrade = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_manager_fk_ed_grade_ddl0");
            HtmlElement actualmajor = doc.GetElementById("ctl00$ContentPlaceHolder1$actual_major_txt");

            name.InnerText = data.PersonalName;
            lastname.InnerText = data.PersonalLastName;
            fullname.InnerText = data.PersonalFullName;
            actualid.InnerText = data.ActualEmploy;
            mellicode.InnerText = data.MelliCode;
            birthdate.InnerText = data.BirthDate;
            actualissue.InnerText = data.ActualIssue;
            fathername.InnerText = data.FatherName;
            actualemploy.InnerText = data.ActualEmploy;

            managergrade.Children[data.ManagerGrade].SetAttribute("selected", "selected");
            actualmajor.InnerText = data.ActualMajor;

            if (data.ActualHighSpeed)
            {
                HtmlElement actualhighspeed = doc.GetElementById("ctl00_ContentPlaceHolder1_actual_high_speed_checkbox");
                actualhighspeed.SetAttribute("checked", "true");

                actualhighspeed.RaiseEvent("onclick");

                data.State = RegisterState.FillData_Personal_Speed;

                return;
            };

            data.State = RegisterState.FillData_Address;
        }

        private void FillData_RequestType()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement requestType = doc.GetElementById("ctl00$ContentPlaceHolder1$customerTypeDdl");

            requestType.Children[data.RequestType - 1].SetAttribute("selected", "selected");                         

            requestType.RaiseEvent("onchange");

            data.State = data.RequestType == 1 ? RegisterState.FillData_Personal : RegisterState.FillData_Company;

        }

        private void Search()
        {            
            HtmlDocument doc = webBrowser.Document;

            HtmlElement searchText = doc.GetElementById("ctl00$ContentPlaceHolder1$sub_id");
            HtmlElement searchBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$searchBtn");


            searchText.InnerText = data.Identity;          

            searchBtn.InvokeMember("click");

            data.State = RegisterState.CheckSearchResult;
        }

        private void Login()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement searchText = doc.GetElementById("ctl00$ContentPlaceHolder1$Login1$userNameTxt");
            HtmlElement passwordText = doc.GetElementById("ctl00$ContentPlaceHolder1$Login1$passwordTxt");
            HtmlElement loginBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$Login1$loginLinkBtn");

            if (SpecialModems.Instance.usernames.Contains(data.Identity))
            {
                searchText.InnerText = special_username;
                passwordText.InnerText = special_password;
            }
            else
            {
                searchText.InnerText = username;
                passwordText.InnerText = password;
            }

            loginBtn.InvokeMember("click");

            data.State = RegisterState.Search;
        }

        private void Starting()
        {
            webBrowser.Navigate(url);

            data.State = RegisterState.Login;
        }

        private void PrintHeader()
        {
            txtReport.Text = data.ToString();
        }

        internal void Log(string message)
        {
            try
            {
                object callback = new object();

                string endpoint = "net.pipe://localhost/Registration/ReportService";

                ChannelFactory<IReportService> pipeFactory =
                   new ChannelFactory<IReportService>(
                      new NetNamedPipeBinding(),
                      new EndpointAddress(endpoint));

                IReportService service = pipeFactory.CreateChannel();

                service.ReportRegistration(data);
            }
            catch (Exception)
            {

            }
            finally
            {
                //Application.Exit();
            }
        }

        internal void Start()
        {
            timer.Stop();

            data.State = RegisterState.Started;

            timer.Interval = interval * 1000;
            timer.Start();
        }

        private void webBrowser_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
    }
}
